package com.yeban.javase.day20.test.test5.jdk;

import com.yeban.javase.day20.test.test5.statics.ICalculator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/11/6
 */
public class DynamicProxyCalculator {

    // 目标对象
    private ICalculator target;

    public DynamicProxyCalculator(ICalculator target) {
        this.target = target;
    }

    // 获取代理对象的实例
    public ICalculator getProxy() {
        // 代理对象
        ICalculator proxy = null;
        // 1.类加载器 classLoader
        ClassLoader classLoader = target.getClass().getClassLoader();
        // 2.实现的接口
        Class<?>[] interfaces = target.getClass().getInterfaces();
        // 3.执行处理器
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 获得执行的目标方法
                String name = method.getName();
                // 编写扩展逻辑的功能
                System.out.println("开始日志追踪：The Method " + name + " begin with" + Arrays.toString(args));
                long l1 = System.currentTimeMillis();
                // 执行目标方法前后，开始日志追踪
                Object result = method.invoke(target, args);
                long l2 = System.currentTimeMillis();
                System.out.println("结束日志追踪：The Method login end with , 耗时" + (l2-l1) + "ms");
                return result;
            }
        };

        proxy = (ICalculator) Proxy.newProxyInstance(classLoader, interfaces, handler);
        return proxy;
    }
}
